<template>
  <div class="user-portrait-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card shadow="never" class="search-card">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item prop="name" label="用户名称">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入用户名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item prop="title" label="问题标题">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入问题标题"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item prop="gender" label="性别">
            <el-select
              v-model="queryParams.gender"
              placeholder="请选择性别"
              clearable
              style="width: 200px"
            >
              <el-option label="男" value="male" />
              <el-option label="女" value="female" />
              <el-option label="未知" value="unknown" />
            </el-select>
          </el-form-item>
          <el-form-item label="活跃度">
            <el-select
              v-model="queryParams.activityLevel"
              placeholder="活跃度"
              clearable
              style="width: 200px"
            >
              <el-option label="高活跃" value="high" />
              <el-option label="中活跃" value="medium" />
              <el-option label="低活跃" value="low" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
            <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
            <el-button
              type="success"
              icon="data-analysis"
              @click="handleAnalyze"
              :disabled="selectedData.length === 0"
            >
              分析选中数据
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 用户列表表格 -->
    <div class="table-section">
      <el-card shadow="never" class="table-card">
        <el-table
          ref="dataTableRef"
          v-loading="loading"
          :data="userList"
          highlight-current-row
          @selection-change="handleSelectionChange"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" align="center" />

          <!-- 用户信息列 -->
          <el-table-column label="用户信息" width="240">
            <template #default="scope">
              <div class="user-info-cell">
                <el-avatar :size="48" :src="scope.row.avatar_url" />
                <div class="user-details">
                  <div class="user-name">{{ scope.row.name }}</div>
                  <div class="user-meta">
                    <el-tag :type="getGenderTagType(scope.row.gender)" size="small" effect="light">
                      {{ getGenderText(scope.row.gender) }}
                    </el-tag>
                    <el-tag
                      :type="getActivityLevelTagType(scope.row)"
                      size="small"
                      effect="light"
                      class="ml-2"
                    >
                      {{ getActivityLevel(scope.row) }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 互动数据列 -->
          <el-table-column label="互动数据" min-width="320">
            <template #default="scope">
              <div class="interaction-grid">
                <div class="interaction-item">
                  <div class="interaction-icon">
                    <el-icon><Star /></el-icon>
                  </div>
                  <div class="interaction-content">
                    <div class="interaction-value">{{ scope.row.voteup_count }}</div>
                    <div class="interaction-label">点赞</div>
                  </div>
                </div>
                <div class="interaction-item">
                  <div class="interaction-icon">
                    <el-icon><ChatDotRound /></el-icon>
                  </div>
                  <div class="interaction-content">
                    <div class="interaction-value">{{ scope.row.reply_count || 0 }}</div>
                    <div class="interaction-label">回复</div>
                  </div>
                </div>
                <div class="interaction-item">
                  <div class="interaction-icon">
                    <el-icon><View /></el-icon>
                  </div>
                  <div class="interaction-content">
                    <div class="interaction-value">{{ scope.row.view_count || 0 }}</div>
                    <div class="interaction-label">浏览</div>
                  </div>
                </div>
                <div class="interaction-item">
                  <div class="interaction-icon">
                    <el-icon><Comment /></el-icon>
                  </div>
                  <div class="interaction-content">
                    <div class="interaction-value">{{ scope.row.comment_count || 0 }}</div>
                    <div class="interaction-label">评论</div>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 活跃度分析列 -->
          <el-table-column label="活跃度分析" width="220">
            <template #default="scope">
              <div class="activity-cell">
                <div class="activity-time">{{ formatTime(scope.row.created_time) }}</div>
                <div class="activity-progress">
                  <el-progress
                    :percentage="calculateActivityScore(scope.row)"
                    :stroke-width="10"
                    :color="getActivityColor(scope.row)"
                    :format="formatActivityLevel"
                  />
                </div>
                <div class="activity-footer">
                  <span class="interaction-score">
                    互动指数: {{ calculateInteractionScore(scope.row) }}
                  </span>
                  <el-tag
                    v-if="isRecent(scope.row)"
                    size="small"
                    effect="light"
                    type="success"
                    class="recent-tag"
                  >
                    新用户
                  </el-tag>
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <!-- <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button type="primary" size="small" plain @click="analyzeSingle(scope.row)">
                分析
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>

        <div class="pagination-wrapper">
          <el-pagination
            v-if="total > 0"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            layout="total, prev, pager, next, jumper"
            @current-change="handleQuery"
          />
        </div>
      </el-card>
    </div>

    <!-- 分析结果区域 -->
    <div v-if="showAnalysis" class="analysis-section">
      <el-divider content-position="left">
        <h3 class="analysis-title">
          <el-icon><DataAnalysis /></el-icon>
          <span>用户画像分析</span>
        </h3>
      </el-divider>

      <div class="chart-grid">
        <!-- 第一行图表 -->
        <div class="chart-row">
          <el-card shadow="never" class="chart-card">
            <div class="chart-header">
              <h4>
                <el-icon><User /></el-icon>
                用户性别分布
              </h4>
            </div>
            <div id="userGenderChart" class="chart-container"></div>
          </el-card>

          <el-card shadow="never" class="chart-card">
            <div class="chart-header">
              <h4>
                <el-icon><TrendCharts /></el-icon>
                用户活跃度分布
              </h4>
            </div>
            <div id="userActivityChart" class="chart-container"></div>
          </el-card>
        </div>

        <!-- 第二行图表 -->
        <div class="chart-row">
          <el-card shadow="never" class="chart-card">
            <div class="chart-header">
              <h4>
                <el-icon><PieChart /></el-icon>
                内容类型分布
              </h4>
            </div>
            <div id="contentTypeChart" class="chart-container"></div>
          </el-card>

          <el-card shadow="never" class="chart-card">
            <div class="chart-header">
              <h4>
                <el-icon><Histogram /></el-icon>
                用户影响力TOP10
              </h4>
            </div>
            <div id="influenceDistributionChart" class="chart-container"></div>
          </el-card>
        </div>

        <!-- 第三行图表 -->
        <div class="chart-row">
          <el-card shadow="never" class="chart-card full-width">
            <div class="chart-header">
              <h4>
                <el-icon><Clock /></el-icon>
                用户行为热力图
              </h4>
            </div>
            <div id="behaviorHeatmapChart" class="chart-container"></div>
          </el-card>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";
import BaseDataApi from "@/api/BaseData";
import { formatTime } from "@/utils/time";
const queryFormRef = ref();
const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
const showAnalysis = ref(false);
const selectedData = ref<any[]>([]);
const userList = ref<any[]>([]);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: "",
  title: "",
  gender: "",
  activityLevel: "",
});

// 获取性别标签类型
const getGenderTagType = (gender) => {
  return gender === "male" ? "primary" : gender === "female" ? "danger" : "info";
};

// 获取性别文本
const getGenderText = (gender) => {
  return gender === "male" ? "男" : gender === "female" ? "女" : "未知";
};

// 查询用户数据
const handleQuery = () => {
  loading.value = true;
  BaseDataApi.getPage(queryParams)
    .then((data) => {
      userList.value = data.list;
      total.value = data.total;
    })
    .finally(() => (loading.value = false));
};

// 重置查询
const handleResetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
};

// 行复选框选中
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  selectedData.value = selection;
};

// 分析选中数据
const handleAnalyze = () => {
  if (selectedData.value.length === 0) {
    ElMessage.warning("请先选择要分析的数据");
    return;
  }

  showAnalysis.value = true;

  nextTick(() => {
    initUserGenderChart();
    initUserActivityChart();
    initContentTypeChart();
    initInfluenceDistributionChart();
    initBehaviorHeatmapChart();
  });
};

// 计算活跃度分数
const calculateActivityScore = (user) => {
  // const hoursAgo = (new Date().getTime() - user.created_time) / (1000 * 60 * 60);
  // const recencyScore = Math.max(0, 100 - (hoursAgo / 24) * 10);

  // const interactionScore = Math.min(
  //   100,
  //   user.voteup_count * 0.5 +
  //     (user.reply_count || 0) * 2 +
  //     (user.view_count || 0) * 0.1 +
  //     (user.comment_count || 0) * 1.5 +
  //     (user.favorites_count || 0) * 1.2
  // );

  return Math.round((user.scores * 100).toFixed(2));
};

// 计算互动指数
const calculateInteractionScore = (user) => {
  return Math.round(
    user.voteup_count * 0.3 + (user.reply_count || 0) * 0.4 + (user.comment_count || 0) * 0.3
  );
};

// 获取活跃度等级
const getActivityLevel = (user) => {
  const score = calculateActivityScore(user);
  if (score > 80) return "高活跃";
  if (score > 60) return "中活跃";
  return "低活跃";
};

// 获取活跃度标签类型
const getActivityLevelTagType = (user) => {
  const level = getActivityLevel(user);
  return level === "高活跃" ? "success" : level === "中活跃" ? "warning" : "info";
};

// 获取活跃度颜色
const getActivityColor = (user) => {
  const score = calculateActivityScore(user);
  if (score > 80) return "#67c23a";
  if (score > 60) return "#e6a23c";
  return "#f56c6c";
};

// 格式化活跃度显示
const formatActivityLevel = (percentage) => {
  return `${percentage}分`;
};

// 判断是否近期用户
const isRecent = (user) => {
  return new Date().getTime() - new Date(user.created_time).getTime() < 7 * 24 * 60 * 60 * 1000;
};

// 1. 用户性别分布图
const initUserGenderChart = () => {
  const chart = echarts.init(document.getElementById("userGenderChart"));

  const genderMap = { male: 0, female: 0, unknown: 0 };
  selectedData.value.forEach((user) => {
    genderMap[user.gender]++;
  });

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)",
    },
    legend: {
      orient: "vertical",
      right: 10,
      top: "center",
    },
    series: [
      {
        name: "性别分布",
        type: "pie",
        radius: ["50%", "70%"],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: "#fff",
          borderWidth: 2,
        },
        label: {
          show: false,
          position: "center",
        },
        emphasis: {
          label: {
            show: true,
            fontSize: "18",
            fontWeight: "bold",
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: genderMap.male, name: "男性", itemStyle: { color: "#3a8ee6" } },
          { value: genderMap.female, name: "女性", itemStyle: { color: "#f56c6c" } },
          { value: genderMap.unknown, name: "未知", itemStyle: { color: "#909399" } },
        ],
      },
    ],
  };

  chart.setOption(option);
  window.addEventListener("resize", () => chart.resize());
};

// 2. 用户活跃度分析图
const initUserActivityChart = () => {
  const chart = echarts.init(document.getElementById("userActivityChart"));

  const activityLevels = { high: 0, medium: 0, low: 0 };
  selectedData.value.forEach((user) => {
    const level = getActivityLevel(user);
    if (level === "高活跃") activityLevels.high++;
    else if (level === "中活跃") activityLevels.medium++;
    else activityLevels.low++;
  });

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)",
    },
    series: [
      {
        name: "活跃度",
        type: "pie",
        radius: ["40%", "70%"],
        center: ["50%", "50%"],
        roseType: "radius",
        itemStyle: {
          borderRadius: 5,
        },
        label: {
          formatter: "{b}: {d}%",
        },
        data: [
          { value: activityLevels.high, name: "高活跃", itemStyle: { color: "#67c23a" } },
          { value: activityLevels.medium, name: "中活跃", itemStyle: { color: "#e6a23c" } },
          { value: activityLevels.low, name: "低活跃", itemStyle: { color: "#f56c6c" } },
        ],
      },
    ],
  };

  chart.setOption(option);
  window.addEventListener("resize", () => chart.resize());
};

// 3. 内容类型分布图
const initContentTypeChart = () => {
  const chart = echarts.init(document.getElementById("contentTypeChart"));

  // 模拟内容类型分布
  const contentTypes = {
    question: Math.floor(selectedData.value.length * 0.4),
    answer: Math.floor(selectedData.value.length * 0.3),
    comment: Math.floor(selectedData.value.length * 0.2),
    share: Math.floor(selectedData.value.length * 0.1),
  };

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{b}: {c} ({d}%)",
    },
    series: [
      {
        name: "内容类型",
        type: "pie",
        radius: "50%",
        label: {
          formatter: "{b}: {d}%",
        },
        data: [
          { value: contentTypes.question, name: "问题", itemStyle: { color: "#3a8ee6" } },
          { value: contentTypes.answer, name: "回答", itemStyle: { color: "#67c23a" } },
          { value: contentTypes.comment, name: "评论", itemStyle: { color: "#e6a23c" } },
          { value: contentTypes.share, name: "分享", itemStyle: { color: "#f56c6c" } },
        ],
      },
    ],
  };

  chart.setOption(option);
  window.addEventListener("resize", () => chart.resize());
};

// 4. 影响力分布图
const initInfluenceDistributionChart = () => {
  const chart = echarts.init(document.getElementById("influenceDistributionChart"));

  // 基于点赞数和回复数计算影响力
  const influenceData = selectedData.value
    .map((user) => ({
      name: user.name,
      value: Math.round(user.voteup_count * 0.7 + (user.reply_count || 0) * 0.3),
    }))
    .sort((a, b) => b.value - a.value)
    .slice(0, 10);

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "value",
      name: "影响力指数",
    },
    yAxis: {
      type: "category",
      data: influenceData.map((item) => item.name),
      axisLabel: {
        interval: 0,
      },
    },
    series: [
      {
        name: "影响力",
        type: "bar",
        data: influenceData,
        itemStyle: {
          color: (params) => {
            const colorList = ["#3a8ee6", "#67c23a", "#e6a23c", "#f56c6c", "#909399"];
            return colorList[params.dataIndex % colorList.length];
          },
        },
      },
    ],
  };

  chart.setOption(option);
  window.addEventListener("resize", () => chart.resize());
};

// 5. 行为热力图
const initBehaviorHeatmapChart = () => {
  const chart = echarts.init(document.getElementById("behaviorHeatmapChart"));

  const hours = Array.from({ length: 24 }, (_, i) => `${i}:00`);
  const days = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];

  const data = [];
  for (let i = 0; i < 7; i++) {
    for (let j = 0; j < 24; j++) {
      data.push([j, i, Math.floor(Math.random() * 100)]);
    }
  }

  const option = {
    tooltip: {
      position: "top",
      formatter: function (params) {
        return `${days[params.value[1]]} ${params.value[0]}:00<br>活跃度: ${params.value[2]}`;
      },
    },
    grid: {
      top: "15%",
      left: "3%",
      right: "4%",
      bottom: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: hours,
      splitArea: {
        show: true,
      },
    },
    yAxis: {
      type: "category",
      data: days,
      splitArea: {
        show: true,
      },
    },
    visualMap: {
      min: 0,
      max: 100,
      calculable: true,
      orient: "horizontal",
      left: "center",
      bottom: "0%",
      inRange: {
        color: ["#e0f3f8", "#abd9e9", "#74add1", "#4575b4", "#313695"],
      },
    },
    series: [
      {
        name: "活跃度",
        type: "heatmap",
        data: data,
        label: {
          show: false,
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };

  chart.setOption(option);
  window.addEventListener("resize", () => chart.resize());
};

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped>
.user-portrait-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-section {
  margin-bottom: 20px;

  .search-card {
    background-color: #fff;
    border-radius: 8px;

    :deep(.el-card__body) {
      padding: 20px;
    }
  }
}

.table-section {
  margin-bottom: 20px;

  .table-card {
    background-color: #fff;
    border-radius: 8px;

    :deep(.el-card__body) {
      padding: 20px;
    }
  }

  .pagination-wrapper {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.analysis-section {
  margin-top: 30px;

  .analysis-title {
    display: flex;
    align-items: center;
    margin: 0;
    font-size: 18px;
    color: #333;

    .el-icon {
      margin-right: 8px;
      color: #3a8ee6;
    }
  }

  .chart-grid {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  .chart-row {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;

    &.single {
      grid-template-columns: 1fr;
    }
  }

  .chart-card {
    background-color: #fff;
    border-radius: 8px;

    &.full-width {
      grid-column: span 2;
    }

    .chart-header {
      padding: 16px 16px 0;
      margin-bottom: 10px;

      h4 {
        display: flex;
        align-items: center;
        margin: 0;
        font-size: 16px;
        color: #333;

        .el-icon {
          margin-right: 8px;
          color: #3a8ee6;
        }
      }
    }

    .chart-container {
      height: 350px;
      padding: 0 16px 16px;
    }
  }
}

.user-info-cell {
  display: flex;
  align-items: center;

  .user-details {
    margin-left: 12px;

    .user-name {
      font-weight: 500;
      margin-bottom: 4px;
    }

    .user-meta {
      display: flex;
      align-items: center;
    }
  }
}

.interaction-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;

  .interaction-item {
    display: flex;
    align-items: center;
    padding: 8px;
    background-color: #f8f9fa;
    border-radius: 6px;

    .interaction-icon {
      width: 32px;
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: rgba(58, 142, 230, 0.1);
      border-radius: 50%;
      margin-right: 10px;

      .el-icon {
        color: #3a8ee6;
        font-size: 16px;
      }
    }

    .interaction-content {
      .interaction-value {
        font-weight: 500;
        margin-bottom: 2px;
      }

      .interaction-label {
        font-size: 12px;
        color: #909399;
      }
    }
  }
}

.activity-cell {
  .activity-time {
    font-size: 13px;
    color: #909399;
    margin-bottom: 8px;
  }

  .activity-progress {
    margin-bottom: 8px;
  }

  .activity-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .interaction-score {
      font-size: 12px;
      color: #909399;
    }

    .recent-tag {
      font-size: 12px;
    }
  }
}

.ml-2 {
  margin-left: 8px;
}
</style>
